import React, { useState, useEffect, useMemo } from "react";
import { get, find, pick, map, mapValues } from "lodash";
import PivotTableUI from "react-pivottable/PivotTableUI";
import { RendererPropTypes } from "@/visualizations/prop-types";
import { formatColumnValue } from "@/lib/utils";

import "react-pivottable/pivottable.css";
import "./renderer.less";

const VALID_OPTIONS = [
  "rows",
  "cols",
  "vals",
  "aggregatorName",
  "valueFilter",
  "sorters",
  "rowOrder",
  "colOrder",
  "derivedAttributes",
  "rendererName",
  "hiddenAttributes",
  "hiddenFromAggregators",
  "hiddenFromDragDrop",
  "menuLimit",
  "unusedOrientationCutoff",
  "controls",
  "rendererOptions",
];

function formatRows(rows, columns, tableColumns) {
  return map(rows, row =>{
    var r = mapValues(row, (value, key) => formatColumnValue(value, find(columns, { name: key }).type));
    for (const key in r) {
      const tc = find(tableColumns, { name : key });
      if (!!tc) {
        if (!tc.visible) {
          delete r[key];
        } else if (!!tc.title && key !== tc.title) {
          r[tc.title] = r[key];
          delete r[key];
        }
      }
    }
    return r;
  });
}

export default function Renderer({ data, options, visualizations, onClickHandler, onOptionsChange }) {
  const [config, setConfig] = useState({ ...options });
  const dataRows = useMemo(() => formatRows(data.rows, data.columns, visualizations[0].options.columns), [data, visualizations]);

  useEffect(() => {
    setConfig({ ...options });
  }, [options]);

  const onChange = updatedOptions => {
    const validOptions = pick(updatedOptions, VALID_OPTIONS);
    setConfig({ ...validOptions });
    onOptionsChange(validOptions);
  };

  // Legacy behavior: hideControls when controls.enabled is true
  const hideControls = get(options, "controls.enabled");
  const hideRowTotals = !get(options, "rendererOptions.table.rowTotals");
  const hideColumnTotals = !get(options, "rendererOptions.table.colTotals");

  const showPortal = window.location.search.includes("show_portal") && localStorage.getItem('colorstyle_mode');
  
  return (
    <div
      className="pivot-table-visualization-container"
      data-hide-controls={hideControls || null}
      data-hide-row-totals={hideRowTotals || null}
      data-hide-column-totals={hideColumnTotals || null}
      data-test="PivotTableVisualization"
      style={showPortal ? {background: "#00000000", color: localStorage.getItem('colorstyle_color')} : null}        
    >
      <PivotTableUI {...pick(config, VALID_OPTIONS)} data={dataRows} onChange={onChange} 
        tableOptions={{
          clickCallback: (e, value, filters, pivotData) => {
            if (!options.clickEnabled) return;
            onClickHandler(filters);
          }
        }}
      />
    </div>
  );
}

Renderer.propTypes = RendererPropTypes;
Renderer.defaultProps = { onOptionsChange: () => {} };
